package com.djx.simple.api;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@RestController
public class TestController {
    @Value("${spring.application.name}")
    private String name;

    private static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(realFileName, StandardCharsets.UTF_8);
        String percentEncodedFileName = encode.replace("\\+", "%20");

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        String contentDispositionValue = "attachment; filename=" +
                percentEncodedFileName +
                ";" +
                "filename*=" +
                "utf-8''" +
                percentEncodedFileName;
        response.setHeader("Content-disposition", contentDispositionValue);
        response.setHeader("download-filename", percentEncodedFileName);
    }

    @GetMapping("whoami")
    public String test() {
        return "我是：" + name;
    }

    /**
     * 通用上传请求
     *
     * @param file 文件对象
     */
    @PostMapping("/upload")
    public String uploadFileWithMinio(MultipartFile file) {
        try {
            String uploadDir = System.getenv("UPLOAD_DIR");
            File file1 = new File(uploadDir, Objects.requireNonNull(file.getOriginalFilename()));
            try (InputStream in = file.getInputStream();
                 OutputStream out = new FileOutputStream(file1);
            ) {
                IOUtils.copy(in, out);
                out.flush();
            }
            // 保存文件至 minio 服务器
            return file1.getAbsolutePath();
        } catch (Exception e) {
            return "failure:" + e.getMessage();
        }
    }

    @GetMapping("download")
    public void download(String fileName, HttpServletResponse response) {
        File file = new File(fileName);
        try (OutputStream out = response.getOutputStream();
             InputStream in = new FileInputStream(file)) {
            setAttachmentResponseHeader(response, file.getName());
            IOUtils.copy(in, out);
            out.flush();
        } catch (Exception e) {
            //
        }
    }
}
